package com.simpleplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;

import com.simpleplayer.services.HTMLResourceExtractor;
import com.simpleplayer.services.LogUtil;
import com.simpleplayer.services.UriUtil;
import com.simpleplayer.views.customview.CustomButton;
import com.simpleplayer.views.customview.CustomDialog;
import com.simpleplayer.views.customview.CustomListDialog;

import java.net.URL;

public class HomeActivity extends AppCompatActivity implements HTMLResourceExtractor.Listener {
    private static final String TAG = "HomeActivity";

    private static final String DEFAULT_URL = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    private static final String DEFAULT_PAGE_URL = "https://media.w3.org/2010/05/sintel";
    private static final int FLING_MIN_DISTANCE = 100;
    private static final int FLING_MIN_VELOCITY = 50;

    private EditText mVideoUriText;
    private EditText mPageUriText;
    private CustomButton mExtractButton;

    private GestureDetector mGestureDetector;

    private Intent mVideoIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.setDebugLevel(LogUtil.MINLEVEL);

        initWindow();
        initView();

        mGestureDetector = new GestureDetector(this, new SimpleOnGestureListenerImpl());

        LogUtil.d(TAG, "Activity " + this + " create");
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        setContentView(R.layout.home_page);
        ViewGroup contentContainer = findViewById(R.id.content_container);
        CustomButton playButton = findViewById(R.id.play_button);
        mExtractButton = findViewById(R.id.extract_button);
        mVideoUriText = findViewById(R.id.video_uri);
        mPageUriText = findViewById(R.id.page_uri);

        mVideoUriText.setHint("请输入视频地址，默认地址: " + DEFAULT_URL);
        mPageUriText.setHint("请输入要提取的网址，默认地址: " + DEFAULT_PAGE_URL);

        contentContainer.setOnTouchListener((v, event) -> mGestureDetector.onTouchEvent(event));
        playButton.setOnClickListener(
                v -> {
                    if (mVideoUriText.getText().toString().isEmpty()) {
                        startUpVideoActivity(DEFAULT_URL);
                    } else {
                        startUpVideoActivity(mVideoUriText.getText().toString());
                    }
                }
        );
        mExtractButton.setOnClickListener(
                v -> {
                    if (mPageUriText.getText().toString().isEmpty()) {
                        HTMLResourceExtractor.getDefault().extract(DEFAULT_PAGE_URL, this);
                    } else {
                        HTMLResourceExtractor.getDefault().extract(mPageUriText.getText().toString(), this);
                    }
                }
        );
    }

    private void initWindow() {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    @Override
    public void onExtractFinish(HTMLResourceExtractor extractor, HTMLResourceExtractor.WebContents webContents) {
        if (webContents == null) {
            LogUtil.d(TAG, "提取网页失败");
            CustomDialog dialog = new CustomDialog(this);
            dialog.setTip("提取网页失败");
            dialog.show();
            return;
        } else {
            LogUtil.d(TAG, "提取网页成功");
        }

        // 网页中无视频资源
        if (webContents.getVideos() == null) {
            LogUtil.d(TAG, "网页 " + webContents.getUri() + " 无视频");
            CustomDialog dialog = new CustomDialog(this);
            dialog.setTip("网页 " + webContents.getUri() + " 未检测到有效视频");
            dialog.show();
            return;
        }

        // 解冻按钮
        mExtractButton.unfreeze();
        // 显示播放列表
        CustomListDialog playlist = new CustomListDialog(this);
        playlist.setTitle("视频资源");
        for (HTMLResourceExtractor.VideoInfo videoInfo : webContents.getVideos()) {
            playlist.addItem(
                    videoInfo.poster,
                    UriUtil.chinesize(getTitleFromVideoInfo(videoInfo)),
                    videoInfo.sources.get(0));
            LogUtil.d(TAG, "title: " + videoInfo.title + ", uri: " + videoInfo.sources.get(0) + ", poster: " + videoInfo.poster);
        }
        playlist.addOnItemClickListener((title, url) -> startUpVideoActivity(url));
        playlist.show();
    }

    private static String getTitleFromVideoInfo(HTMLResourceExtractor.VideoInfo videoInfo) {
        try {
            if (videoInfo.title == null || videoInfo.title.isEmpty()) {
                String path = new URL(videoInfo.sources.get(0)).getPath();
                if (path != null && !path.isEmpty()) {
                    int nameIndex = path.lastIndexOf("/");
                    if (nameIndex == -1) {
                        return path;
                    } else {
                        return path.substring(nameIndex + 1);
                    }
                }
            } else {
                return videoInfo.title;
            }
        } catch (Exception ex) {
            LogUtil.e(TAG, "catch exception when extract name from " + videoInfo.sources.get(0));
            ex.printStackTrace();
        }

        return "无标题视频";
    }

    private void startUpVideoActivity(String url) {
        mVideoIntent = new Intent(this, VideoActivity.class);
        mVideoIntent.putExtra("video-src", url);
        startActivity(
                mVideoIntent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    private void resumeVideoActivity() {
        LogUtil.d(TAG, "resume VideoActivity");
        if (mVideoIntent == null) return;

        mVideoIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(
                mVideoIntent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    private class SimpleOnGestureListenerImpl extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float x = e1.getX() - e2.getX();
            float y = e1.getY() - e2.getY();
            if(x > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY){
                if (x > Math.abs(y)) {
                    LogUtil.i(TAG, "向右滑动");
                    resumeVideoActivity();
                }
            }

            return true;
        }
    }
}